/* Copyright (c) [Year] [name of copyright holder]
 * [Software Name] is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *      http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.gitee.empty_null.core.filter;

import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;

import java.util.UUID;

/**
 * @author xuhainan
 * @date 2023/8/25 13:41
 * @region hefei
 */
public class TraceWebRequestInterceptor implements WebRequestInterceptor {
    private static final String TRACE_ID = "traceId";

    @Override
    public void preHandle(@NotNull WebRequest request) throws Exception {
        String traceId = UUID.randomUUID().toString();
        MDC.put(TRACE_ID, traceId);
    }

    @Override
    public void postHandle(@NotNull WebRequest request, ModelMap model) throws Exception {

    }

    @Override
    public void afterCompletion(@NotNull WebRequest request, Exception ex) throws Exception {
        MDC.remove(TRACE_ID);
    }
}
